import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
import './index.scss'
import { App, Button, Card, Form, Input, message, Row, Select, Space, Table, Tag } from "antd";
import {  type OptionGroupType, type OptionType, type SelectOptionDto, type SelectOptionType } from "@/types";
import { useForm } from "antd/es/form/Form";
import {  deleteSelectOption, queryOptionGroup, querySelectOption } from "@/apis/commonService";
import { EditOutlined } from "@ant-design/icons";
import { useLocation } from "react-router-dom";
import SelectOptionForm from "@/components/OptionForm/SelectOptionForm";
import dayjs from "dayjs";

const SelectOption = forwardRef((props, ref) => {
    const { modal } = App.useApp();
    // 表格数据
    const [tableData,setTableData] = useState<SelectOptionType[]>([]);
    // 总记录数
    const [total,setTotal] = useState<number>(0);
    // 查询条件
    const [queryForm,setQueryForm] = useState<SelectOptionDto>({
        current: 1,
        size: 6
    });
    // 查询表单标识
    const [form] = Form.useForm();
    // 组别选项
    const [optionGroup,setOptionGroup] = useState<OptionType[]>();
    // 获取state传参
    const location = useLocation();
    // 弹框组件标识
    const selectOptionFormRef = useRef(null);

    const columns = [
        {
            title: '字典编码',
            dataIndex: 'value'
        },
        {
            title: '字典标签',
            dataIndex: 'label',
        },
        {
            title: '字典排序',
            dataIndex: 'sort',
        },
        {
            title: '状态',
            dataIndex: 'status',
            render: (value: number,record: SelectOptionType) => {
                return (
                    <Tag color={ record.status === 1 ? 'processing' : 'error' }>
                        {
                            record.status === 1 ? '正常' : '停用'
                        }
                    </Tag>
                )
            }
        },
        {
            title: '备注',
            dataIndex: 'remark'
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            render: (createTime: string,record: OptionGroupType) => {
                return (
                <span>{ dayjs(createTime).format('YYYY-MM-DD HH:mm:ss') }</span>
                )
            }
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record: SelectOptionType) => (
            <Space size="middle">
                <Button onClick={() => editRow(record)} type="primary" icon={<EditOutlined />}>修改</Button>
            </Space>
            ),
        },
    ];

    // 加载中标识
    const [loading, setLoading] = useState(false);
    // 当前选中的数据行id
    const [selectDataIds,setSelectDataIds] = useState<string[]>([]);
    // 当前选中的数据
    const [selectedDatas,setSelectDatas] = useState<SelectOptionType[]>([]);
    
    /** 表格选中回调  */
    const tabSelectChange = (selectedRowKeys: React.Key[], selectedRows: SelectOptionType[]) => {
        setSelectDataIds(selectedRowKeys as string[]);
        setSelectDatas(selectedRows as SelectOptionType[]);
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    }

    /** 改变查询条件  */
    const changeSeleteCondition = (params: SelectOptionDto) => {
        setQueryForm(params);
    }

    /** 查询  */
    const queryTableData = async () => {
        try {
            setLoading(true);            
            const res = await querySelectOption(queryForm);
            console.log("查询结果Res====>",res);
            // 若当前查询的记录数为0 且当前页数不为1 则当前页数减少1页后重新查询
            if (res.data.records.length === 0 && queryForm.current != 1) {
                setQueryForm({
                    ...queryForm,
                    current: queryForm.current - 1
                })
            }
            setTableData(res.data.records);
            setTotal(res.data.total);
        } catch (error) {
            console.log(error);
        }finally{
            setLoading(false);
        }
    }

    /** 新增  */
    const add = () => {
        const optionGroupKey: string = form.getFieldValue('optionGroupKey');
        selectOptionFormRef.current.open({'optionGroupKey': optionGroupKey});
    }

    /** 删除 */
    const deleteTableData = async () => {
        if (selectDataIds.length === 0) {
            message.warning('请先选择数据再进行操作！')
            return;
        }
        modal.confirm({
            title: '温馨提示',
            content: '是否删除选中的数据？',
            okText: '确认',
            cancelText: '取消',
            async onOk(){
               const res = await deleteSelectOption(selectDataIds);
                if (res.code === 200) {
                    message.success("删除成功！");
                    await queryTableData();
                }else {
                    message.error(res.msg);
                } 
            },
            onCancel: () => {

            }
        })
    }    

    /** 面试评价  */
    const editRow = (val: SelectOptionType) => {
        selectOptionFormRef.current.open(val);
    }

    /** 设置表格默认选项行背景色  */
    const setDefaultBgColor = (row: SelectOptionType) => {
        if (row.isDefault) {
            console.log("触发=====>",row.label);
            return 'row-default-bg-color'
        }
    }

    /** 初始化页面选项  */
    const isExcuteFlag = useRef(false);
    const initOptionInfo = async () => {
        // 获取组别信息，作为组别选项
        const res = await queryOptionGroup();
        const optionGroupInfos: OptionGroupType[] = res.data.records as OptionGroupType[];
        const optionGroupList =  optionGroupInfos.map(item => {
            return {
                label: item.groupDesc,
                value: item.groupKey
            }
        });
        setOptionGroup(optionGroupList);
        
        // 从路由中获取state传参，若有传参则说明是通过路由进入页面，此时使用传递的组别标识作为查询条件
        const optionGroupKey = location.state?.optionGroupKey || '';
        if (optionGroupKey) {
            setQueryForm({
                ...queryForm,
                optionGroupKey: optionGroupKey,
            });
            form.setFieldValue("optionGroupKey",optionGroupKey);
            isExcuteFlag.current = true;
        }
    }

    /** 页面初始化 或 查询条件发生改变时 调用查询 */
    useEffect(() => {
        if (!location.state?.optionGroupKey || isExcuteFlag.current) {
            queryTableData();   
        }
    },[queryForm]);

    /** 进入页面时，初始化选项信息  */
    useEffect(() => {
        initOptionInfo();
    },[location.state]);

    
    return (
        <div className="select-option">
            <Card className="card" title="查询条件">
                <Form
                    form={form}
                    layout="inline"
                    name="select-option"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ width: '100%' }}
                    initialValues={{ status: queryForm.status }}
                    onFinish={(val) => changeSeleteCondition({...queryForm,...val})}
                    autoComplete="off"
                >
                    <Row style={{ width: '100%' }}>
                        <Form.Item<SelectOptionType>
                            label="组别名称"
                            name="optionGroupKey"
                        >
                            <Select
                                placeholder="请选择组别名称"
                                style={{ width: 200 }}
                                options={optionGroup}
                                />
                        
                        </Form.Item>
                        
                        <Form.Item<SelectOptionType>
                            label="字典标签"
                            name="label"
                        >
                            <Input placeholder="请输入字典标签"/>
                        </Form.Item>

                        <Form.Item<SelectOptionType>
                            label="状态"
                            name="status"
                        >
                            <Select
                                placeholder="请选择"
                                allowClear
                                style={{ width: 200 }}
                                options={[
                                    {
                                        label: '启用',
                                        value: 1
                                    },
                                    {
                                        label: '禁用',
                                        value: 0
                                    }
                                ]}
                            />
                        </Form.Item>
                    </Row>

                    <Row justify='end' style={{ width: '100%',marginTop: '20px' }}>
                        <Form.Item label={null}>
                            <Button type="primary" htmlType="button" onClick={add}>
                                新增
                            </Button>
                        </Form.Item>
                        <Form.Item label={null}>
                            <Button type="primary" htmlType="button" onClick={deleteTableData}>
                                删除
                            </Button>
                        </Form.Item>
                        <Form.Item label={null}>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                        </Form.Item>
                    </Row>
                </Form>
            </Card>

            <Card className="card" title="查询结果">
                <Table
                    rowKey="id"
                    loading={loading} 
                    dataSource={tableData} 
                    columns={columns}
                    rowClassName={(row) => setDefaultBgColor(row)}
                    rowSelection={{ type: 'checkbox',onChange: tabSelectChange,selectedRowKeys: selectDataIds,preserveSelectedRowKeys: true }}
                    pagination={{
                        showQuickJumper: true,
                        total: total,
                        showTotal: (total) => `共 ${total} 条数据`,
                        current: queryForm.current,
                        pageSize: queryForm.size,
                        showSizeChanger: true,
                        onChange: (current,size) => changeSeleteCondition({...form.getFieldsValue(),current,size}),
                        pageSizeOptions: [6,10,20,50,100]
                    }}  
                />
            </Card>
            <SelectOptionForm ref={selectOptionFormRef} reQuery={queryTableData}></SelectOptionForm>
        </div>
    )

    useImperativeHandle(ref, () => ({
    }));
});

export default SelectOption;